import http from '../../utils/http.js'
import BuyCart from '../../utils/buycar.js'
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgDomain: app.globalData.imgDomain,
    swiperHeight:300,
    indicatorDots: true,
    autoplay: false,
    interval: 5000,
    duration: 150,
    selectedAttr:{},
    selectedFlavor:"",
    detail:{
      goodsId:'',
      mImgList:[],
      attrList:[],
      groupBuyList:[]
    },
    nodes: [],
    cartCount:0,
    isLogin: false,
    wxPhone: '',
    isGroup:false,
    group:{}
  },
  getCouponList() {
    let me = this;
    let userId = wx.getStorageSync("userId");
    if (!userId) {
      return;
    }
    http.request({
      url: 'coupon/getCouponByUserId/' + userId,
      loadTip: '加载中',
      success: res => {
        if (res && res.length > 0) {
          let couponNames = "";
          res.forEach((item) => {
            couponNames += "【" + item.name + "】,"
          });
          couponNames = couponNames.substr(0, couponNames.length - 1);
          wx.showModal({
            title: '优惠券',
            content: '您有 ' + res.length + ' 张优惠券' + couponNames,
            cancelText: '先逛逛',
            confirmText: '立即查看',
            success: res => {
              if (res.confirm) {
                wx.navigateTo({
                  url: '../coupon/coupon'
                })
              }
            }
          })
        }
      }
    });
  },
  getSmsCode(e) {
    let me = this;
    let phone = e.detail;
    if (phone) {
      me.setData({
        wxPhone: phone
      });
    }
    if (!me.data.wxPhone) {
      return;
    }
    http.request({
      url: 'user/smsCode/' + me.data.wxPhone,
      loadTip: '正在加载',
      method: 'get',
      success: res => {
        if (res) {
          wx.showToast({
            icon: 'success',
            title: '验证码已发送'
          })
        }
      }
    });
  },
  bindAccount(e) {
    let me = this;
    if (!e.detail.phone) {
      wx.showToast({
        icon: 'none',
        title: '请输入手机号',
      })
      return;
    }
    if (!e.detail.smscode) {
      wx.showToast({
        icon: 'none',
        title: '请输入短信验证码',
      })
      return;
    }
    http.request({
      url: 'user/register2',
      loadTip: '正在请求',
      data: {
        phone: e.detail.phone,
        smscode: e.detail.smscode,
        wxkey: app.getSessionKey(),
        sex: 1
      },
      success: res => {
        me.setData({
          isLogin: false
        });
        wx.setStorageSync("userId", res.userId);
        wx.setStorageSync("phone", res.userName);
        me.getCouponList();
        setTimeout(() => {
          me.getCartCount();
        }, 200)
      }
    });
  },
  getPhoneNumber(e) {
    let me = this;
    http.request({
      url: 'user/getPhoneNumberOfWx2',
      loadTip: '授权中',
      data: {
        encrypData: e.detail.encryptedData,
        iv: e.detail.iv,
        wxKey: app.getSessionKey()
      },
      success: res => {
        let phoneInfo = JSON.parse(res);
        me.setData({
          wxPhone: phoneInfo.phoneNumber
        });
      }
    });
  },

  gobuy(){
    let me = this;
    if (!app.isBind()) {
      this.setData({
        isLogin: true
      });
      return;
    }
    let userId = wx.getStorageSync("userId");
    BuyCart.add(me.data.selectedAttr.goodsAttrId, 1, userId, (res) => {
      wx.navigateTo({
        url: '../buycar/buycar',
      })
    }, me.data.selectedFlavor);
  },

  gobuycart(){
    if (!app.isBind()) {
      this.setData({
        isLogin: true
      });
      return;
    }
    wx.navigateTo({
      url: '../buycar/buycar',
    })
  },

  addCart(e) {
    let me = this;
    if (!app.isBind()) {
      this.setData({
        isLogin: true
      });
      return;
    }
    let userId = wx.getStorageSync("userId");
    BuyCart.add(me.data.selectedAttr.goodsAttrId, 1, userId, (res) => {
      wx.showToast({
        title: '已加入购物车'
      })
      me.getCartCount();
    }, me.data.selectedFlavor);
  },

  getCartCount() {
    let me = this;
    let userId = wx.getStorageSync("userId");
    if (!userId) {
      return;
    }
    http.request({
      url: 'cart/count/' + userId,
      method: 'get',
      success: res => {
        me.setData({
          cartCount: res
        });
      }
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let systemInfo = wx.getSystemInfoSync();
    let width = systemInfo.screenWidth;

    this.setData({
      swiperHeight: width
    });
    this.setData({
      detail:{
        goodsId:options.id
      }
    });
    this.loadGoodDetail();
  },

  loadGoodDetail(){
    let me = this;
    http.request({
      url:'good/idforwx/'+me.data.detail.goodsId,
      loadTip: '加载中',
      method:'get',
      success:res=>{
        wx.setNavigationBarTitle({
          title: res.goodsName
        })
        let groupBuy = res.groupBuyList.find(item => {
          return item.goodsAttrId == res.attrList[0].goodsAttrId
        })
        let isGroup = false;
        let group = {}
        if (groupBuy) {
          isGroup = true;
          group = groupBuy;
        }
        me.setData({
          detail: res,
          selectedAttr: res.attrList[0],
          isGroup: isGroup,
          group: group,
          selectedFlavor: res.flavorList && res.flavorList.length > 0 ? res.flavorList[0].flavorName : ""
        });
      }
    });
  },
  selectFlavor(e){
    this.setData({
      selectedFlavor: e.currentTarget.dataset.select.flavorName
    })
    console.log(this.data.selectedFlavor);
  },
  selectWeight(e) {
    let me=this;
    let selectAttr = e.currentTarget.dataset.select;
    let groupBuy = me.data.detail.groupBuyList.find(item=>{
      return item.goodsAttrId == selectAttr.goodsAttrId
    })
    let isGroup = false;
    let group = {}
    if(groupBuy){
      isGroup = true;
      group = groupBuy;
      wx.showToast({
        icon:'none',
        title: '您选择的磅数可参与拼团'
      })
    }
    this.setData({
      selectedAttr: selectAttr,
      isGroup:isGroup,
      group:group
    });
  },

  goGroupBuy(){
    let me=this;
    wx.navigateTo({
      url: '../order/addorder?isGroup=true&goodsAttrId=' + me.data.selectedAttr.goodsAttrId
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getCartCount();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})